package com.uboot.baidu.src;


import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.uboot.baidu.src.com.baidu.translate.demo.TransApi;
import com.uboot.uyibai.core.exception.UBootException;

public class BaiduMain {

    // 在平台申请的APP_ID 详见 http://api.fanyi.baidu.com/api/trans/product/desktop?req=developer
    private static final String APP_ID = "20181024000224944";
    private static final String SECURITY_KEY = "B8GtXZe6Fj2UM8Ss1OWI";

    public static String fanyi(String query) {
        TransApi api = new TransApi(APP_ID, SECURITY_KEY);
        String res = api.getTransResult(query, "auto", "zh");
        if(StrUtil.isNotBlank(res)){
            try{
                JSONObject jsonObject = (JSONObject) JSONObject.parse(res);
                JSONArray jsonArray = jsonObject.getJSONArray("trans_result");
                if(jsonArray != null){

                    StringBuilder stringBuilder = new StringBuilder();
                    for (Object o : jsonArray) {
                        JSONObject dst = (JSONObject) JSONObject.parse(o.toString());
                        stringBuilder.append(dst.getString("dst"));
                    }
                    return stringBuilder.toString();
                }
            }catch (Exception e){
                throw new UBootException("翻译失败：" + e.getMessage());
            }
        }
        return null;
    }

}
